import { emailVerifyCode } from '@/api/flow/auth';
import { MAILBOX } from '@/utils/mixins/sendCode/type';

export default {
   data() {
    return {
      // form
      form: this.$form.createForm(this),

      // state
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    };
  },
  methods: {
    // send code email
     sendEmailCode() {
      const fields = ['email'];
      let data = this.form.getFieldsValue(fields);
      data = { ...data, template_type: MAILBOX };

      this.sendCode(fields, data);
    },

    // handleRetrieve
    handleRetrieve(e) {
      e.preventDefault();

      const { state } = this;

      state.loginBtn = true;

      this.validateFieldsForm()
        .then(() => {
          this.retrievePassword()
            .then(() => {
              const fields = this.form.getFieldsValue(['email']);
              this.$emit('retrieve', fields);
            })
            .finally(() => {
              state.loginBtn = false;
            });
        })
        .catch(() => {
          state.loginBtn = false;
        });
    },

    // form validateFields
    validateFieldsForm() {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFields }
        } = this;

        const validateFieldsKey = ['email', 'code'];

        validateFields(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve();
            return false;
          }
          reject(false);
        });
      });
    },

    // Retrieve password
    retrievePassword() {
      const validateFieldsKey = ['email', 'code'];

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey);

        emailVerifyCode(fields)
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
  }
};
